import {
  useState, useRef, useEffect, useCallback,
} from 'react'
import { AppState, AppStateStatus } from 'react-native'

interface Props {
  totalSecond: number
  start?: boolean
  onEnd?: () => void
}

const useCountdown = (props: Props) => {
  const { totalSecond, start = true, onEnd = () => {} } = props
  const [appState, setAppState] = useState<AppStateStatus>('active')
  const [count, setCount] = useState(totalSecond)

  const time = useRef({
    wentBackgroundAt: 0, // 切换到后台的时间戳
    diff: 0, // 在后台暂停了多少秒
  })

  useEffect(() => {
    setCount(totalSecond)
  }, [totalSecond])

  useEffect(() => {
    if (count === 0) {
      onEnd()
      setCount(totalSecond)
    }
  }, [count, onEnd, setCount, totalSecond])

  const handleAppStateChange = useCallback(
    (currentAppState: AppStateStatus) => {
      if (['active', 'background'].includes(currentAppState) && start) {
        const { wentBackgroundAt } = time.current
        if (currentAppState === 'active') {
          const diff = Math.round((Date.now() - wentBackgroundAt) / 1000)
          time.current.diff = diff
        }
        if (currentAppState === 'background') {
          time.current.wentBackgroundAt = Date.now()
        }
        setAppState(currentAppState)
      }
    },
    [start],
  )

  const onCount = useCallback(
    (timer:number, data:number) => {
      const value = data - time.current.diff - 1
      time.current.diff = 0
      if (value <= 0) {
        clearInterval(timer)
      }
      return Math.max(value, 0)
    },
    [],
  )

  useEffect(() => {
    AppState.addEventListener('change', handleAppStateChange)
  }, [handleAppStateChange])

  useEffect(() => {
    let timer = 0
    if (start && appState === 'active') {
      setCount((currentCount) => onCount(timer, currentCount))
      timer = setInterval(() => {
        setCount((currentCount) => onCount(timer, currentCount))
      }, 1000)
    }
    return () => clearInterval(timer)
  }, [start, appState, onCount])

  return ({
    m: String(Math.floor(count / 60)).padStart(2, '0'), // 剩余分钟数
    s: String(Math.floor(count % 60)).padStart(2, '0'), // 剩余秒数
    remainingSeconds: count, // 剩余的总秒数
  })
}

export default useCountdown
